import { cloneDeep, forEach, includes, map, merge, round } from 'lodash-es';
import dayjs from 'dayjs';
import { useRequest } from '@/hooks/requestHooks.js';
import { useWatch } from '@/hooks/useWatch.js';
import { barSeriesItem, lineSeriesItem } from '@/views/hooks.js';
import { arrowClassMap } from '@/constants.js';
import { basicTitle, basicLineXAxis, basicLineYAxis, basicLineLegend } from '@/components/chart/options/baseOptions.js';
import {
  getOvStatistics,
  // entEngAmount,
  getEngJCTrend,
  getDSECRatio,
  getDSECTrend,
  getDeviceSysTree,
  getInsAreaEnergy,
  entEngChartData,
  energyConsumptionRatio,
} from '@/api/index.js';

// 概览数据统计
export const useOvStatistics = params => {
  const [data, loading, run] = useRequest(getOvStatistics, {
    deafaultParams: [params],
    manual: true,
  });
  return [data, loading, run];
};
// 监测渲染
// export const useJCOverview = code => {
//   const amountParams = ref({
//     belong: '1', //查询区域或者项目或者企业（1：区域，0:企业、项目）
//     enterpriseCode: null, //企业id
//     projectCode: '', //项目id
//     buildingCode: code, //区域id
//     projectType: 'JC',
//   });
//   const [entEngData, , runAmount] = useRequest(entEngAmount, { manual: true });

//   return [amountParams, entEngData, runAmount];
// };
// 监测能耗/碳排chart
export const dateTypeWatch = (
  params,
  daterange,
  yearrange,
  rangeType,
  paramsKey = { dateStart: 'dateStart', dateEnd: 'dateEnd' },
) => {
  useWatch(
    () => params.value.dateType,
    (n, o) => {
      if (n !== o) {
        if (n !== 'y') {
          daterange.value = rangeType.value[n].default;
          params.value[paramsKey.dateStart] = daterange.value[0];
          params.value[paramsKey.dateEnd] = daterange.value[1];
        } else {
          yearrange.value.sYear = rangeType.value.y.default[0];
          yearrange.value.eYear = rangeType.value.y.default[1];
          params.value[paramsKey.dateStart] = yearrange.value.sYear;
          params.value[paramsKey.dateEnd] = yearrange.value.eYear;
        }
      }
    },
  );
};
export const runChartWatch = (params, run, needMatch = true) => {
  useWatch(
    () => cloneDeep(params),
    n => {
      const dateTypeMatch = {
        d: 10,
        m: 7,
        y: 4,
      };
      if (needMatch) {
        if (
          (n?.inId || n?.contractType || n?.enterpriseCode || n?.isHome) &&
          dateTypeMatch[n.dateType] === n.dateEnd.length
        ) {
          run(n);
        }
      } else {
        if (n?.buildingCode || n?.belong || n?.inId) {
          run(n);
        }
      }
    },
    { deep: true },
  );
};
const seriesArr = (isMonth = false) => {
  return Array.from({ length: isMonth ? 4 : 3 }, (_, i) => {
    return i === 0
      ? merge({}, barSeriesItem, { yAxisIndex: 0 })
      : merge({}, lineSeriesItem, { yAxisIndex: i < 2 ? 0 : 1 });
  });
};
const abidingDimensions = [
  { key: 'thisValue', EC: '能耗量', CE: '碳排量' },
  { key: 'trend', EC: '能耗趋势', CE: '碳排趋势' },
  { key: 'chainValue', EC: '环比', CE: '环比' },
  { key: 'togetherValue', EC: '同比', CE: '同比' },
];
const commonOpts = {
  color: ['#4992ff', '#ee6666', '#eda422', '#5afe5d'],
  dataset: { source: [] },
  series: seriesArr(),
  tooltip: {
    formatter: params => {
      if (Array.isArray(params) && params.length > 0) {
        params.splice(1, 1);
        let str = `<div class="u-mb5">${params[0].axisValue}</div>`;
        forEach(params, e => {
          let seriesName = e.seriesName;
          let value = e.value[e.dimensionNames[e.encode.y]] ?? '--';
          if (includes(seriesName, '环比') || includes(seriesName, '同比')) {
            const sign = Math.sign(value);
            value = value !== '--' ? `${value}% <i class="${arrowClassMap.get(sign)} u-fs14"></i>` : `${value}%`;
          }
          str += `<ul class="u-df-spb u-mb5"><li>${e.marker}${seriesName}</li><li class="u-ml30">${value}</li></ul>`;
        });
        return str;
      }
      return '';
    },
  },
  xAxis: { ...basicLineXAxis },
  yAxis: [
    merge({}, basicLineYAxis, {
      name: '单位：tce',
      nameTextStyle: { fontSize: 12 },
    }),
    merge({}, basicLineYAxis, {
      name: '单位：%',
      nameTextStyle: { fontSize: 12, align: 'right' },
    }),
  ],
  legend: {
    icon: 'rect',
    itemWidth: 10,
    itemHeight: 4,
    x: 'center',
    y: 10,
    padding: [10, 25],
  },
  grid: { bottom: 5, top: 45, left: 60, right: 20, containLabel: true },
  dataZoom: null,
};
export const useJCChart = rangeType => {
  const lineExtraOpts1 = ref(
    merge({}, commonOpts, {
      dataset: {
        source: [],
        dimensions: ['date', ...map(abidingDimensions, v => ({ name: v.key, displayName: v.EC }))],
      },
    }),
  );
  const lineExtraOpts2 = ref(
    merge({}, commonOpts, {
      dataset: {
        source: [],
        dimensions: ['date', ...map(abidingDimensions, v => ({ name: v.key, displayName: v.CE }))],
      },
      yAxis: [{ name: '单位：tco2' }],
    }),
  );

  const dateRangeEC = ref(rangeType.value.d.default);
  const dateRangeCE = ref(rangeType.value.d.default);
  const yearRangeEC = ref({ sYear: null, eYear: null });
  const yearRangeCE = ref({ sYear: null, eYear: null });
  const commonParams = {
    dateType: 'd',
    energyType: 0,
    inId: null,
    projectType: 'JC',
  };
  const ECParams = ref({
    ...commonParams,
    istco2e: false,
    dateStart: dateRangeEC.value[0],
    dateEnd: dateRangeEC.value[1],
  });
  const CEParams = ref({
    ...commonParams,
    istco2e: true,
    dateStart: dateRangeCE.value[0],
    dateEnd: dateRangeCE.value[1],
  });
  const [, ECLoading, runEC] = useRequest(getEngJCTrend, {
    manual: true,
    defaultParams: [ECParams.value],
    onSuccess: res => {
      // if (!res.data?.length) lineExtraOpts1.value.yAxis[0].nameTextStyle.padding = [0, 0, 0, 60];
      lineExtraOpts1.value.dataset.source = map(res.data, v => ({ ...v, trend: v.thisValue }));
    },
  });
  const [, CELoading, runCE] = useRequest(getEngJCTrend, {
    manual: true,
    defaultParams: [CEParams.value],
    onSuccess: res => {
      // if (!res.data?.length) lineExtraOpts2.value.yAxis[0].nameTextStyle.padding = [0, 0, 0, 60];
      lineExtraOpts2.value.dataset.source = map(res.data, v => ({ ...v, trend: v.thisValue }));
    },
  });
  const handleECDaterange = val => {
    ECParams.value.dateStart = val?.[0] ?? null;
    ECParams.value.dateEnd = val?.[1] ?? null;
  };
  const handleCEDaterange = val => {
    CEParams.value.dateStart = val?.[0] ?? null;
    CEParams.value.dateEnd = val?.[1] ?? null;
  };
  const handleECYearrange = () => {
    ECParams.value.dateStart = yearRangeEC.value.sYear;
    ECParams.value.dateEnd = yearRangeEC.value.eYear;
  };
  const handleCEYearrange = () => {
    CEParams.value.dateStart = yearRangeCE.value.sYear;
    CEParams.value.dateEnd = yearRangeCE.value.eYear;
  };

  dateTypeWatch(ECParams, dateRangeEC, yearRangeEC, rangeType);
  dateTypeWatch(CEParams, dateRangeCE, yearRangeCE, rangeType);
  runChartWatch(ECParams.value, runEC);
  runChartWatch(CEParams.value, runCE);
  useWatch([() => ECParams.value.dateType, () => CEParams.value.dateType], ([n1, n2]) => {
    lineExtraOpts1.value.series = seriesArr(n1 === 'm' ? true : false);
    lineExtraOpts2.value.series = seriesArr(n2 === 'm' ? true : false);
  });

  return [
    dateRangeEC,
    dateRangeCE,
    yearRangeEC,
    yearRangeCE,
    lineExtraOpts1,
    lineExtraOpts2,
    ECParams,
    CEParams,
    ECLoading,
    CELoading,
    handleECDaterange,
    handleCEDaterange,
    handleECYearrange,
    handleCEYearrange,
    runEC,
    runCE,
  ];
};
export const useTGChart = (rangeType, engUnit) => {
  const textStyle = {
    color: '#f5f5f5',
    fontWeight: 'normal',
    fontSize: 16,
    lineHeight: 18,
  };
  const commonOpts = {
    title: [
      merge({}, basicTitle, {
        text: '能耗趋势',
        top: 55,
        left: 15,
        textStyle,
      }),
      merge({}, basicTitle, {
        text: '收益趋势',
        textStyle,
        left: 15,
      }),
    ],
    tooltip: {
      formatter: params => {
        if (Array.isArray(params) && params.length > 0) {
          let str = `<div class="u-mb5">${params[0].axisValue}</div>`;
          forEach(params, e => {
            let seriesName = e.seriesName;
            let value = e.value[e.dimensionNames[e.encode.y]] ?? '--';
            if (
              e.dimensionNames[e.encode.y] === 'energyEarningsConservationCost' &&
              chartParams.value.contractType === 'SHARE'
            ) {
              value = `${value} (占比: ${e.value.energyEarningsConservationRatio ?? '-'}%)`;
            }
            if (includes(seriesName, '环比') || includes(seriesName, '同比')) {
              const sign = Math.sign(value);
              value = value !== '--' ? `${value}% <i class="${arrowClassMap.get(sign)} u-fs14"></i>` : `${value}%`;
            }
            str += `<ul class="u-df-spb u-mb5"><li>${e.marker}${seriesName}</li><li class="u-ml30">${value}</li></ul>`;
          });
          return str;
        }
        return '';
      },
    },
    axisPointer: {
      link: { xAxisIndex: 'all' },
    },
    color: ['#26d5d5', '#4992ff', '#eda422', '#f53019', '#5afe5d', '#f58819', '#fe5a5a', '#d5d526'],
    dataZoom: null,
  };
  const lineExtraOpts1 = ref(merge({}, commonOpts));
  const chartParams = ref({
    inId: null,
    contractType: null,
    dateType: 'd',
    energyType: 0,
    projectType: 'TG',
    dateStart: rangeType.value.d.default[0],
    dateEnd: rangeType.value.d.default[1],
  });
  const [, loading, runChart] = useRequest(entEngChartData, {
    defaultParams: [chartParams.value],
    manual: true,
    onSuccess: res => {
      setChartOpt();
      if (getDimensionsByType()[chartParams.value.contractType]) {
        map(getDimensionsByType()[chartParams.value.contractType], (v, i) => {
          lineExtraOpts1.value.dataset[i].dimensions = v;
          lineExtraOpts1.value.dataset[i].source = res.data;
        });
      } else {
        lineExtraOpts1.value.dataset = { dimensions: [], source: [] };
      }
      setSeriesByType();
      lineExtraOpts1.value.yAxis[0].name = `单位：${engUnit.value}`;
    },
  });
  const getDimensionsByType = () => {
    return {
      CONVENTION: [
        [
          'energyValueDate',
          { name: 'energyBasisValue', displayName: '基准能耗' },
          { name: 'energyConsumeValue', displayName: '实际能耗' },
          { name: 'energyConservationValue', displayName: '节能量' },
          { name: 'energyConservationValueRatio', displayName: '节能率' },
        ],
        [
          'energyValueDate',
          { name: 'energyBasisCost', displayName: '基准费用' },
          { name: 'energyConsumeCost', displayName: '实际费用' },
          { name: 'energyEarningsConservationCost', displayName: '项目收益' },
        ],
      ],
      SHARE: [
        [
          'energyValueDate',
          { name: 'energyBasisValue', displayName: '基准能耗' },
          { name: 'energyConsumeValue', displayName: '实际能耗' },
          { name: 'energyConsumeValueRatio', displayName: '实际能耗环比' },
          { name: 'energyConservationValue', displayName: '节能量' },
          { name: 'energyConservationValueRatio', displayName: '节能率' },
        ],
        [
          'energyValueDate',
          { name: 'energyBasisCost', displayName: '基准费用' },
          { name: 'energyConsumeCost', displayName: '实际费用' },
          { name: 'energyConservationCost', displayName: '节能总收益' },
        ],
        [
          'energyValueDate',
          { name: 'energyConservationCost', displayName: '项目节能总收益' },
          { name: 'energyEarningsConservationCost', displayName: '综能项目总收益' },
          { name: 'energyConservationCostRatio', displayName: '综能项目收益环比' },
        ],
      ],
      ENSURE: [
        [
          'energyValueDate',
          { name: 'energyBasisValue', displayName: '基准能耗' },
          { name: 'energyConsumeValue', displayName: '实际能耗' },
          { name: 'energyConsumeValueRatio', displayName: '实际能耗环比' },
          { name: 'energyConservationValue', displayName: '节能量' },
          { name: 'energyConservationValueRatio', displayName: '节能率' },
        ],
        [
          'energyValueDate',
          { name: 'energyGuaranteeConservationValue', displayName: '保证节能量' },
          { name: 'energyConservationValue', displayName: '实际节能量' },
          { name: 'energyConservationValueGap', displayName: '节能量差值' },
        ],
        [
          'energyValueDate',
          { name: 'energyBasisCost', displayName: '标准服务费' },
          { name: 'energyEarningsConservationCost', displayName: '实际项目收益' },
          { name: 'energyConservationCostRatio', displayName: '项目收益环比' },
        ],
      ],
    };
  };
  const setSeriesByType = () => {
    let seriesSet = [];
    if (chartParams.value.contractType === 'CONVENTION') {
      lineExtraOpts1.value.legend[0].data = ['基准能耗', '实际能耗'];
      lineExtraOpts1.value.legend[1].data = ['基准费用', '实际费用'];
      for (let i = 0; i < 2; i++) {
        const item = lineExtraOpts1.value.dataset[i];
        const arr = Array.from({ length: item.dimensions.length - 1 }, (_, idx) => {
          if (idx === 0) {
            const obj = {
              type: 'line',
              smooth: true,
              showSymbol: false,
              lineStyle: { type: 'dashed' },
            };
            if (i === 0) {
              obj.datasetIndex = 0;
              obj.xAxisIndex = 0;
              obj.yAxisIndex = 0;
            } else {
              obj.datasetIndex = 1;
              obj.xAxisIndex = 2;
              obj.yAxisIndex = 2;
            }
            return obj;
          } else if (idx === 1) {
            const obj = {
              type: 'bar',
              showSymbol: false,
              smooth: true,
              barWidth: 12,
            };
            if (i === 0) {
              obj.datasetIndex = 0;
              obj.xAxisIndex = 0;
              obj.yAxisIndex = 0;
            } else {
              obj.datasetIndex = 1;
              obj.xAxisIndex = 2;
              obj.yAxisIndex = 2;
            }
            return obj;
          } else {
            const obj = {
              type: 'line',
              symbol: 'none',
              lineStyle: { opacity: 0 },
            };
            if (i === 0) {
              obj.datasetIndex = 0;
              obj.xAxisIndex = 0;
              obj.yAxisIndex = 1;
            } else {
              obj.datasetIndex = 1;
              obj.xAxisIndex = 2;
              obj.yAxisIndex = 3;
            }
            return obj;
          }
        });
        seriesSet = seriesSet.concat(arr);
      }
    }
    if (chartParams.value.contractType === 'SHARE') {
      lineExtraOpts1.value.legend[0].data = ['基准能耗', '实际能耗', '实际能耗环比'];
      lineExtraOpts1.value.legend[1].data = ['基准费用', '实际费用'];
      lineExtraOpts1.value.legend[2].data = ['项目节能总收益', '综能项目总收益', '综能项目收益环比'];
      for (let i = 0; i < 3; i++) {
        const item = lineExtraOpts1.value.dataset[i];
        const arr = Array.from({ length: item.dimensions.length - 1 }, (_, idx) => {
          if (idx === 0) {
            const obj =
              i < 2
                ? {
                    type: 'line',
                    smooth: true,
                    showSymbol: false,
                    lineStyle: { type: 'dashed' },
                  }
                : {
                    type: 'bar',
                    barWidth: 12,
                  };
            if (i === 0) {
              obj.datasetIndex = 0;
              obj.xAxisIndex = 0;
              obj.yAxisIndex = 0;
            } else if (i === 1) {
              obj.datasetIndex = 1;
              obj.xAxisIndex = 2;
              obj.yAxisIndex = 2;
            } else {
              obj.datasetIndex = 2;
              obj.xAxisIndex = 4;
              obj.yAxisIndex = 4;
            }
            return obj;
          } else if (idx === 1) {
            const obj = {
              type: 'bar',
              showSymbol: false,
              smooth: true,
              barWidth: 12,
            };
            if (i === 0) {
              obj.datasetIndex = 0;
              obj.xAxisIndex = 0;
              obj.yAxisIndex = 0;
            } else if (i === 1) {
              obj.datasetIndex = 1;
              obj.xAxisIndex = 2;
              obj.yAxisIndex = 2;
            } else {
              obj.barGap = '-100%';
              obj.datasetIndex = 2;
              obj.xAxisIndex = 4;
              obj.yAxisIndex = 4;
            }
            return obj;
          } else if (idx === 2) {
            const obj =
              i === 1
                ? {
                    type: 'line',
                    symbol: 'none',
                    lineStyle: { opacity: 0 },
                  }
                : {
                    type: 'line',
                    smooth: true,
                    showSymbol: false,
                  };
            if (i === 0) {
              obj.datasetIndex = 0;
              obj.xAxisIndex = 0;
              obj.yAxisIndex = 1;
            } else if (i === 1) {
              obj.datasetIndex = 1;
              obj.xAxisIndex = 2;
              obj.yAxisIndex = 3;
            } else {
              obj.datasetIndex = 2;
              obj.xAxisIndex = 4;
              obj.yAxisIndex = 5;
            }
            return obj;
          } else {
            const obj = {
              type: 'line',
              symbol: 'none',
              lineStyle: { opacity: 0 },
            };
            if (i === 0) {
              obj.datasetIndex = 0;
              obj.xAxisIndex = 0;
              obj.yAxisIndex = 1;
            } else if (i === 1) {
              obj.datasetIndex = 1;
              obj.xAxisIndex = 2;
              obj.yAxisIndex = 3;
            } else {
              obj.datasetIndex = 2;
              obj.xAxisIndex = 4;
              obj.yAxisIndex = 5;
            }
            return obj;
          }
        });
        seriesSet = seriesSet.concat(arr);
      }
    }
    if (chartParams.value.contractType === 'ENSURE') {
      lineExtraOpts1.value.legend[0].data = ['基准能耗', '实际能耗', '实际能耗环比'];
      lineExtraOpts1.value.legend[1].data = ['保证节能量', '实际节能量'];
      lineExtraOpts1.value.legend[2].data = ['标准服务费', '实际项目收益', '项目收益环比'];
      for (let i = 0; i < 3; i++) {
        const item = lineExtraOpts1.value.dataset[i];
        const arr = Array.from({ length: item.dimensions.length - 1 }, (_, idx) => {
          if (idx === 0) {
            const obj = {
              type: 'line',
              smooth: true,
              showSymbol: false,
              lineStyle: { type: 'dashed' },
            };
            if (i === 0) {
              obj.datasetIndex = 0;
              obj.xAxisIndex = 0;
              obj.yAxisIndex = 0;
            } else if (i === 1) {
              obj.datasetIndex = 1;
              obj.xAxisIndex = 2;
              obj.yAxisIndex = 2;
            } else {
              obj.datasetIndex = 2;
              obj.xAxisIndex = 4;
              obj.yAxisIndex = 4;
            }
            return obj;
          } else if (idx === 1) {
            const obj = {
              type: 'bar',
              showSymbol: false,
              smooth: true,
              barWidth: 12,
            };
            if (i === 0) {
              obj.datasetIndex = 0;
              obj.xAxisIndex = 0;
              obj.yAxisIndex = 0;
            } else if (i === 1) {
              obj.datasetIndex = 1;
              obj.xAxisIndex = 2;
              obj.yAxisIndex = 2;
            } else {
              obj.datasetIndex = 2;
              obj.xAxisIndex = 4;
              obj.yAxisIndex = 4;
            }
            return obj;
          } else if (idx === 2) {
            const obj =
              i === 1
                ? {
                    type: 'line',
                    symbol: 'none',
                    lineStyle: { opacity: 0 },
                  }
                : {
                    type: 'line',
                    smooth: true,
                    showSymbol: false,
                  };
            if (i === 0) {
              obj.datasetIndex = 0;
              obj.xAxisIndex = 0;
              obj.yAxisIndex = 1;
            } else if (i === 1) {
              obj.datasetIndex = 1;
              obj.xAxisIndex = 2;
              obj.yAxisIndex = 3;
            } else {
              obj.datasetIndex = 2;
              obj.xAxisIndex = 4;
              obj.yAxisIndex = 5;
            }
            return obj;
          } else {
            const obj = {
              type: 'line',
              symbol: 'none',
              lineStyle: { opacity: 0 },
            };
            if (i === 0) {
              obj.datasetIndex = 0;
              obj.xAxisIndex = 0;
              obj.yAxisIndex = 1;
            } else if (i === 1) {
              obj.datasetIndex = 1;
              obj.xAxisIndex = 2;
              obj.yAxisIndex = 3;
            } else {
              obj.datasetIndex = 2;
              obj.xAxisIndex = 4;
              obj.yAxisIndex = 5;
            }
            return obj;
          }
        });
        seriesSet = seriesSet.concat(arr);
      }
    }
    lineExtraOpts1.value.series = seriesSet;
  };
  const setChartOpt = () => {
    if (chartParams.value.contractType === 'CONVENTION') {
      const cObj = {
        title: [{}, { top: '55%' }],
        grid: [
          { bottom: 20, top: 110, left: 80, right: 15, height: '29%' },
          { bottom: 10, top: '65%', left: 80, right: 15, height: '29%' },
        ],
        legend: [
          merge({}, basicLineLegend, {
            data: [],
            x: 'center',
            y: 75,
          }),
          merge({}, basicLineLegend, {
            data: [],
            x: 'center',
            y: '59%',
          }),
        ],
        dataset: Array.from({ length: 2 }, () => ({ dimensions: [], source: [] })),
      };
      const axisObj = {
        xAxis: [
          merge({}, basicLineXAxis, { gridIndex: 0 }),
          { gridIndex: 0, show: false },
          merge({}, basicLineXAxis, { gridIndex: 1 }),
          { gridIndex: 1, show: false },
        ],
        yAxis: [
          merge({}, basicLineYAxis, {
            name: '单位：tce',
            nameTextStyle: { fontSize: 12 },
            gridIndex: 0,
          }),
          merge({}, basicLineYAxis, {
            name: '单位：%',
            nameTextStyle: { fontSize: 12, align: 'right' },
            axisLabel: { show: false },
            gridIndex: 0,
          }),
          merge({}, basicLineYAxis, {
            name: '单位：元',
            nameTextStyle: { fontSize: 12 },
            gridIndex: 1,
          }),
          merge({}, basicLineYAxis, {
            name: '单位：%',
            nameTextStyle: { fontSize: 12, align: 'right' },
            axisLabel: { show: false },
            gridIndex: 1,
          }),
        ],
      };
      lineExtraOpts1.value = merge({}, lineExtraOpts1.value, cObj);
      lineExtraOpts1.value.xAxis = axisObj.xAxis;
      lineExtraOpts1.value.yAxis = axisObj.yAxis;
    }
    if (includes(['SHARE', 'ENSURE'], chartParams.value.contractType)) {
      const identicalOpt = {
        dataset: Array.from({ length: 3 }, () => ({ dimensions: [], source: [] })),
        xAxis: [
          merge({}, basicLineXAxis, { gridIndex: 0 }),
          { gridIndex: 0, show: false },
          merge({}, basicLineXAxis, { gridIndex: 1 }),
          { gridIndex: 1, show: false },
          merge({}, basicLineXAxis, { gridIndex: 2 }),
          { gridIndex: 2, show: false },
        ],
        yAxis: [
          merge({}, basicLineYAxis, {
            name: '单位：tce',
            nameTextStyle: { fontSize: 12 },
            gridIndex: 0,
          }),
          merge({}, basicLineYAxis, {
            name: '单位：%',
            nameTextStyle: { fontSize: 12, align: 'right' },
            axisLabel: { show: false },
            gridIndex: 0,
          }),
          merge({}, basicLineYAxis, {
            name: '单位：元',
            nameTextStyle: { fontSize: 12 },
            gridIndex: 1,
          }),
          merge({}, basicLineYAxis, {
            name: '单位：%',
            nameTextStyle: { fontSize: 12, align: 'right' },
            axisLabel: { show: false },
            gridIndex: 1,
          }),
          merge({}, basicLineYAxis, {
            name: '单位：元',
            nameTextStyle: { fontSize: 12 },
            gridIndex: 2,
          }),
          merge({}, basicLineYAxis, {
            name: '单位：%',
            nameTextStyle: { fontSize: 12, align: 'right' },
            axisLabel: { show: false },
            gridIndex: 2,
          }),
        ],
      };
      const getExtraOpt = () => {
        const legendArr = [
          merge({}, basicLineLegend, { data: [], x: 'center' }),
          merge({}, basicLineLegend, { data: [], x: 'center' }),
          merge({}, basicLineLegend, { data: [], x: '25%' }),
        ];
        const sObj = {
          grid: [
            { bottom: 0, top: 110, left: 80, right: 15, height: '17%' },
            { bottom: 0, top: '50%', left: 80, right: 15, height: '17%' },
            { bottom: 0, top: '77%', left: 80, right: 15, height: '17%' },
          ],
          title: [{}, { top: '41%' }],
          legend: merge([], legendArr, [{ y: 75 }, { y: '43%' }, { y: '71%' }]),
        };
        const eObj = {
          grid: [
            { bottom: 0, top: 110, left: 80, right: 15, height: '17%' },
            { bottom: 0, top: '46%', left: 80, right: 15, height: '17%' },
            { bottom: 0, top: '77%', left: 80, right: 15, height: '17%' },
          ],
          title: [{}, { top: '68%' }],
          legend: merge([], legendArr, [{ y: 75 }, { y: '41%' }, { y: '71%' }]),
        };

        return chartParams.value.contractType === 'SHARE' ? sObj : eObj;
      };

      lineExtraOpts1.value = merge({}, lineExtraOpts1.value, { ...identicalOpt, ...getExtraOpt() });
    }
  };
  runChartWatch(chartParams.value, runChart);
  const dateRange1 = ref(rangeType.value.d.default);
  const yearRange1 = ref({ sYear: null, eYear: null });
  const disabledDateStart1 = ref({
    disabledDate: time => {
      if (yearRange1.value.eYear) {
        return (
          dayjs(time) > dayjs(yearRange1.value.eYear) || dayjs(time) < dayjs(yearRange1.value.eYear).subtract(2, 'year')
        );
      }
    },
  });
  const disabledDate1 = ref({
    disabledDate: time => {
      return dayjs(time) < dayjs(yearRange1.value.sYear) || dayjs(time) > dayjs(yearRange1.value.sYear).add(2, 'year');
    },
  });
  const handleDaterange1 = val => {
    chartParams.value.dateStart = val?.[0] ?? null;
    chartParams.value.dateEnd = val?.[1] ?? null;
  };
  const handleYearrange1 = () => {
    chartParams.value.dateStart = yearRange1.value.sYear;
    chartParams.value.dateEnd = yearRange1.value.eYear;
  };
  dateTypeWatch(chartParams, dateRange1, yearRange1, rangeType);

  return [
    chartParams,
    loading,
    lineExtraOpts1,
    dateRange1,
    yearRange1,
    disabledDateStart1,
    disabledDate1,
    handleDaterange1,
    handleYearrange1,
  ];
};

// 监测设备系统能耗占比
export const useDSECRatio = rangeType => {
  const extraPieOpts = ref({
    // grid: { bottom: '8%', top: '8%', left: 10 },
    title: {
      text: '系统能耗占比',
      left: '31.5%',
      top: '51%',
      textAlign: 'center',
      textVerticalAlign: 'middle',
      textStyle: { fontSize: 12 },
    },
    tooltip: {
      trigger: 'item',
      formatter: '占比: {d}%<br />{b}: {c}',
    },
    legend: {
      type: 'scroll',
      show: true,
      orient: 'vertical',
      x: null,
      y: 'center',
      right: 0,
      itemWidth: 10,
      itemHeight: 10,
      itemStyle: { borderWidth: 0 },
      textStyle: { fontSize: 11 },
      pageIconSize: 10,
      pageTextStyle: { color: '#7f889a' },
    },
    series: [
      {
        name: '',
        type: 'pie',
        radius: ['50%', '70%'],
        center: ['32%', '52%'],
        label: { fontSize: 10 },
        // itemStyle: {
        //   borderRadius: 10,
        //   borderColor: '#fff',
        //   borderWidth: 2,
        // },
        data: [{ name: '', value: '' }],
      },
    ],
  });
  const ratioParams = ref({
    dateType: 'd',
    sDate: rangeType.value.d.default[0],
    eDate: rangeType.value.d.default[1],
    buildingCode: null,
  });
  const [, ratioLoading, runRatio] = useRequest(getDSECRatio, {
    defaultParams: [ratioParams.value],
    manual: true,
    onSuccess: res => {
      extraPieOpts.value.series[0].data = map(res.data, v => ({
        name: `${v.equSysName} (kWh)`,
        value: round(v.energyQuantity, 2),
      }));
    },
  });

  const handleRatioDate = dateParams => {
    ratioParams.value.dateType = dateParams.dateType;
    ratioParams.value.sDate = dateParams.startTime;
    ratioParams.value.eDate = dateParams.endTime;
  };
  runChartWatch(ratioParams.value, runRatio, false);

  return [ratioParams, extraPieOpts, ratioLoading, handleRatioDate];
};
// 设备系统能耗趋势
export const useDSECTrend = rangeType => {
  const lineExtraOpts = ref(
    merge({}, commonOpts, {
      dataset: {
        dimensions: ['date', ...map(abidingDimensions, v => ({ name: v.key, displayName: v.EC }))],
      },
      yAxis: [{ name: '单位：kWh' }],
      grid: { left: 0, right: 0 },
    }),
  );

  const dateRangeTr = ref(rangeType.value.d.default);
  const yearRangeTr = ref({ sYear: null, eYear: null });
  const trendParams = ref({
    energyType: '',
    buildingCode: null, //机构编码
    dateType: 'd', //时间类型，d-日，m-月。y-年
    sDate: dateRangeTr.value[0], //开始时间
    eDate: dateRangeTr.value[1], //结束时间
    equSysName: null, //设备系统名称
  });
  const [dSysList, , runDSys] = useRequest(getDeviceSysTree, {
    manual: true,
    onSuccess: res => {
      if (res.data?.length) {
        trendParams.value.equSysName = res.data[0]?.id ?? null;
      }
    },
  });
  const [, trendLoading, runTrend] = useRequest(getDSECTrend, {
    manual: true,
    onSuccess: res => {
      if (!res.data?.length) lineExtraOpts.value.yAxis[0].nameTextStyle.padding = [0, 0, 0, 60];
      lineExtraOpts.value.dataset.source = map(res.data, v => ({ ...v, trend: v.thisValue }));
    },
  });
  const handleTrEngType = val => {
    dSysList.value = [];
    trendParams.value.equSysName = null;
    runDSys({ energyType: val === '总' ? '' : val });
  };
  const handleTrDaterange = val => {
    trendParams.value.sDate = val?.[0] ?? null;
    trendParams.value.eDate = val?.[1] ?? null;
  };
  const handleTrYearrange = () => {
    trendParams.value.sDate = yearRangeTr.value.sYear;
    trendParams.value.eDate = yearRangeTr.value.eYear;
  };
  const handleSysName = val => {
    trendParams.value.equSysName = val;
  };

  dateTypeWatch(trendParams, dateRangeTr, yearRangeTr, rangeType, { dateStart: 'sDate', dateEnd: 'eDate' });
  runChartWatch(trendParams.value, runTrend, false);
  useWatch(
    () => trendParams.value.dateType,
    n => (lineExtraOpts.value.series = seriesArr(n === 'm' ? true : false)),
  );
  useWatch(
    () => trendParams.value.buildingCode,
    n => runDSys({ enterpriseCode: n }),
  );

  return [
    trendParams,
    dSysList,
    lineExtraOpts,
    dateRangeTr,
    yearRangeTr,
    trendLoading,
    handleTrEngType,
    handleTrDaterange,
    handleTrYearrange,
    handleSysName,
  ];
};
// 监测机构/楼栋/楼层能耗统计
export const useBuildingECStatics = (rangeType, type) => {
  const ECSDaterange = ref(rangeType.value.d.default);
  const ECSYearrange = ref({ sYear: null, eYear: null });
  const areaECParams = ref({
    projectType: type,
    inId: null,
    areaId: null,
    dateType: 'd',
    dateStart: ECSDaterange.value[0],
    dateEnd: ECSDaterange.value[1],
    isTop: 'yes',
  });
  const [consumeData, , runConsume] = useRequest(getInsAreaEnergy, { manual: true });
  const handleECSDaterange = val => {
    areaECParams.value.dateStart = val?.[0] ?? null;
    areaECParams.value.dateEnd = val?.[1] ?? null;
  };
  const handleECSYearrange = () => {
    areaECParams.value.dateStart = ECSYearrange.value.sYear;
    areaECParams.value.dateEnd = ECSYearrange.value.eYear;
  };

  dateTypeWatch(areaECParams, ECSDaterange, ECSYearrange, rangeType);
  useWatch(areaECParams, n => runConsume(n), { deep: true });

  return [areaECParams, consumeData, ECSDaterange, ECSYearrange, handleECSDaterange, handleECSYearrange];
};

export const findPNodeAndSiblings = (tree, id) => {
  let result = [];
  let parentNode = null;
  const traverse = (nodes, id) => {
    for (let node of nodes) {
      if (node.children) {
        for (let child of node.children) {
          if (child.id === id) {
            result = node.children; // Capture the parent's siblings (including the parent itself)
            parentNode = node; // Capture the parent node
            return true;
          }
        }
        const found = traverse(node.children, id);
        if (found) {
          return true;
        }
      }
    }
    return false;
  };

  traverse(tree, id);
  return [result, parentNode];
};
// 各项能源能耗占比
export const useEnergyCRatio = rangeType => {
  const extraPieOpts2 = ref({
    color: ['#76e612', '#efef12', '#e87f16', '#e61c1c'],
    // grid: { bottom: '8%', top: '8%', left: 10 },
    title: {
      text: ['{a|0}{b|tce}'].join('\n'),
      left: '30%',
      top: '42%',
      textAlign: 'center',
      textStyle: {
        rich: {
          a: {
            color: '#fff',
            fontSize: 30,
            lineHeight: 30,
            fontWeight: 'bold',
          },
          b: {
            color: '#f65d45',
            fontSize: 14,
            padding: [0, 0, -6, 0],
            fontWeight: 'bold',
          },
        },
      },
      subtext: '能源能耗总量',
      subtextStyle: { fontSize: 14, color: '#c0c4cc' },
      itemGap: 20,
    },
    legend: {
      type: 'scroll',
      show: true,
      orient: 'vertical',
      x: null,
      y: 'center',
      right: 0,
      itemWidth: 10,
      itemHeight: 10,
      // formatter: function (name) {},
      textStyle: {
        color: 'auto',
        rich: {
          a: {
            fontSize: 14,
            color: '#fff',
            padding: [0, 15, 0, 0],
          },
          b1: {
            fontSize: 18,
            fontWeight: 'bold',
            color: '#76e612',
          },
          b2: {
            fontSize: 18,
            fontWeight: 'bold',
            color: '#efef12',
          },
          b3: {
            fontSize: 18,
            fontWeight: 'bold',
            color: '#e87f16',
          },
          b4: {
            fontSize: 18,
            fontWeight: 'bold',
            color: '#e61c1c',
          },
          c: {
            fontSize: 14,
            color: '#fff',
            padding: [0, 15, 0, 0],
          },
          d: {
            fontSize: 18,
            fontWeight: 'bold',
          },
        },
      },
      itemStyle: { borderWidth: 0 },
      // textStyle: { fontSize: 11 },
      pageIconSize: 10,
      pageTextStyle: { color: '#7f889a' },
    },
    series: [
      {
        type: 'pie',
        radius: ['50%', '70%'],
        center: ['30%', '52%'],
        label: { fontSize: 10 },
        data: [{ name: '', value: '' }],
      },
    ],
  });
  const ratioParams2 = ref({
    inId: null,
    dateType: 'd',
    // energyType: 'ELECTRICITY',
    projectType: '',
    dateStart: rangeType.value.d.default[0],
    dateEnd: rangeType.value.d.default[1],
  });
  const [, ratioLoading2, runRatio] = useRequest(energyConsumptionRatio, {
    defaultParams: [ratioParams2.value],
    manual: true,
    onSuccess: res => {
      extraPieOpts2.value.title.text = [`{a|${res?.data?.[0].value1 ?? '-'}}{b|tce}`].join('\n');
      extraPieOpts2.value.series[0].data = map(res.data, v => {
        if (v.key !== '能源能耗总量') {
          return { name: v.key, value: v.value1, bfb: v.value2 };
        }
      });
      let data = extraPieOpts2.value.series[0].data.filter(item => typeof item !== 'undefined');
      extraPieOpts2.value.series[0].data = data;
      extraPieOpts2.value.legend.formatter = function (name) {
        let num;
        let bfb;
        for (let i = 0, l = data.length; i < l; i++) {
          if (data[i].name == name) {
            num = data[i].value;
            bfb = data[i].bfb;
          }
        }
        let arr;
        if (name.includes('电')) {
          arr = ['{a|' + name + '能能耗}', '{b1|' + num + '}{c|tce}', '{d|' + bfb + '}'];
        } else if (name.includes('水')) {
          arr = ['{a|' + name + '能能耗}', '{b2|' + num + '}{c|tce}', '{d|' + bfb + '}'];
        } else if (name.includes('气')) {
          arr = ['{a|' + name + '能能耗}', '{b3|' + num + '}{c|tce}', '{d|' + bfb + '}'];
        } else if (name.includes('热')) {
          arr = ['{a|' + name + '能能耗}', '{b4|' + num + '}{c|tce}', '{d|' + bfb + '}'];
        }
        return arr?.join('');
      };
    },
  });

  const handleRatioDate2 = dateParams => {
    ratioParams2.value.dateType = dateParams.dateType;
    ratioParams2.value.dateStart = dateParams.startTime;
    ratioParams2.value.dateEnd = dateParams.endTime;
  };
  runChartWatch(ratioParams2.value, runRatio, false);

  return [ratioParams2, extraPieOpts2, ratioLoading2, handleRatioDate2];
};
